package edu.hubu.ReceivesCommand;

import java.util.Scanner;

public class ReceivesCommandLineData {

    public static void main(String[] args) {
        //TODO:1.从命令行接收数据
        int[] x = new int[10];  //存储数据
        //从命令行传入参数
        for (int i = 0; i < args.length; i++) {
            x[i] = Integer.parseInt(args[i]);
        }
        //打印接收的数据
        System.out.println("从命令行接受的数据：");
        for (int i = 0; i < args.length; i++) {
            System.out.print(x[i] + " ");
        }
        System.out.println();

        //TODO:2.对接收的数据进行从小到大排序（冒泡排序）
        bubbleSort(x);
        //打印排序好的数据
        System.out.println("经冒泡排序后的数据：");
        for (int i : x) {
            System.out.print(i + " ");
        }
        System.out.println();

        //TODO:3.对已排序好的数据进行折半查找
        System.out.println("请输入需要查找的数据：");
        Scanner sc = new Scanner(System.in);
        int value = sc.nextInt();

        int index = binSearch(x, value);
        if (index != -1) {
            System.out.println(value + "所在位置是：" + (index + 1));
        } else {
            System.out.println("未找到" + value + "所在的位置!");
        }

    }

    /*冒泡排序，从小到大*/
    public static void bubbleSort(int[] x) {
        for (int i = 0; i < x.length - 1; i++) {
            for (int j = 0; j < (x.length - 1) - i; j++) {
                if (x[j] > x[j + 1]) {
                    int temp = x[j];
                    x[j] = x[j + 1];
                    x[j + 1] = temp;
                }
            }
        }
    }

    /*折半查找*/
    private static int binSearch(int[] x, int value) {
        //初始化下限和上限的索引值
        int low = 0;
        int high = x.length;
        while (low <= high) {
            int mid = (low + high) / 2;
            if (x[mid] == value) return mid;
            else if (value < x[mid])
                //说明value在前半区
                high = mid - 1;
            else
                //说明value在后半区
                low = mid + 1;
        }
        //若未找到，则返回-1
        return -1;
    }
}
